<?php

class nRouter {

	protected $routes = array();

	/** @return nRouter */
	public static function i() {
		static $instance;
		if ($instance)
			return $instance;
		else
			return $instance = new self();
	}

	public function __construct() {
		$this->routes = nCore::i()->getConfig('router/routes');
	}

	public function route($url = null) {
		if ($url === null)
			$url = isset($_SERVER['PATH_INFO'])
				? $_SERVER['PATH_INFO']
				: (isset($_SERVER['REQUEST_URI']) ? $_SERVER['REQUEST_URI'] : '/');

		$routed = false;
		foreach ($this->routes as $name => $route) {
			$route = new $route['class']($route['options']);
			if ($route instanceof nRoute) {
				$params = $route->match($url);
				if ($params) {
					$route->call($params);
					$routed = true;
					break;
				}
			}
		}
		if (!$routed) {
			header("HTTP/1.0 404 Not Found");
			header('Content-type: text/plain');
			echo '404 Not Found';
		}
	}

	public function url($name, $params = array()) {
		$route = new $this->routes[$name]['class']($this->routes[$name]['options']);
		return $route->url($params);
	}

}